import wxApi from '../../utils/wxApi'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {}, //存放用户地址信息
    cart: [], //购物车数据
    allChecked: false, //是否全选
    totalPrice: 0, //总价格
    totalNum: 0 //总数量
  },

  // 在onShow生命周期中初始化页面数据（收货地址，购物车列表，是否全选 合计）
  onShow: function () {
    let address = wx.getStorageSync('address') || {};
    // console.log(address);
    this.setData({
      address
    });


    let cart = wx.getStorageSync('cart') || [];
    console.log(cart);
    this.updateCart(
      cart
    );
  },


  /* 获取购物车数据 */
  updateCart(cart) {
    let allChecked = true;
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(item => {
      if (item.checked) {
        totalPrice += item.goods_price * item.num;
        totalNum += item.num;
      } else {
        allChecked = false;
      }
    });
    allChecked = cart.length ? allChecked : false
    this.setData({
      cart,
      allChecked,
      totalNum,
      totalPrice
    });
    wx.setStorageSync('cart', cart)
  },

  //某条商品数据被选中事件处理
  onItemCheckChange(e) {
    /* 
      1.获取被选中的商品id
      2.获取商品当前的选中状态 然后取反
      3.需要重新计算的内容
    */

    //获取被选中的商品id
    let goodsId = e.currentTarget.dataset.id;
    //获取购物车信息 根据与商品id找到当前的商品信息
    let {
      cart
    } = this.data;
    let index = cart.findIndex(item => item.goods_id === goodsId);
    let curGoods = cart[index];
    curGoods.checked = !curGoods.checked;
    this.updateCart(cart)

  },

  //全选按钮回调函数
  onAllCheckClick(e) {
    //1.获取当前按钮状态 allChecked
    //2.allChexked状态取非
    //3.获取购物车数据，把allChexked赋值给所有数据的checked
    //4.更新数据
    console.log("全选按钮回调函数");
    let {
      allChecked,
      cart
    } = this.data;
    allChecked = !allChecked;
    cart.forEach(item => item.checked = allChecked);
    this.updateCart(cart);
  },


  //商品加减事件
  handleItemNumEdit(e) {
    console.log("商品加减", e);
    /* 
    1.要加减的num  -1 || +1
    2.获取当前商品的id
    3.通过当前的商品id获取商品信息
    4.在当前商品信息中直接操作num属性
    5.调用自定义的更新函数 更新到页面中
    */
    let {id,num} = e.currentTarget.dataset;
    let {cart} = this.data;
    let index = cart.findIndex(item =>item.goods_id===id);
    let goodsInfo = cart[index];
    /* 
    1.当商品数量为1的时候 用户点击了减号
    2.删除当前商品
    */
    if (goodsInfo.num === 1 && num === -1) {
      wx.showModal({
        title: '提示',
        content: '是否移除此商品',
        success:(res)=> {
          if (res.confirm) {
            cart.splice(index, 1);
            this.updateCart(cart);
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }else{
      goodsInfo.num += num;
      this.updateCart(cart);
    }
  },

//点击结算按钮
  onPayClick:async function(e){
    /* 
      1.判断是否拥有收货地址
      2.购物车有没有数据
      3.有没有商品被选中
      4.跳转pay页面
    */

    let {address,totalNum} = this.data;
    if(!address.userName) return await wxApi.showToast('请选择收货地址');

    if(!totalNum) return await wxApi.showToast('还没有选择商品');

    wx.navigateTo({
      url: '/pages/pay/pay',
    })
  },


  /* 获取收货地址 */
  getAddress: async function () {
    console.log('settings', wxApi)

    try {
      let settings = await wxApi.getSetting();
      console.log(settings);
      let addressSuccess = settings.authSetting['scope.address']
      console.log(addressSuccess);
      if (!addressSuccess) await wdxApi.openSetting();
      let address = await wxApi.chooseAddress();
      console.log('地址', address);
      address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo;

      wx.setStorageSync('address', address);
      this.setData({
        address
      })
    } catch (err) {
      console.log(err);
    }
  }

})